package com.suse.service.community.config;

import com.suse.common.config.response.R;
import com.suse.common.config.response.SimpleCode;
import com.suse.common.util.request.RequestUtil;
import com.suse.common.util.response.ResponseUtil;
import com.suse.service.community.constant.RoleConstant;
import com.suse.service.community.util.AntPatternUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * <p>
 * Security配置类
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-09-05 22:37
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers(AntPatternUtil.getStaticAntPatterns());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 授权请求
        http.authorizeRequests()
                .antMatchers(
                "/user/setting.html",
                    "/user/upload",
                    "/comment/save",
                    "/letter/**",
                    "/notice/**",
                    "/like",
                    "/follow",
                    "/unfollow"
                ).hasAnyAuthority(
                        RoleConstant.USER,
                RoleConstant.ADMIN,
                RoleConstant.MODERATOR
                ).antMatchers(
                        "/discuss/setTop",
                "/discuss/setEssence"
                ).hasAnyAuthority(
                        RoleConstant.MODERATOR)
                .antMatchers(
            "/discuss/delete"
                ).hasAnyAuthority(
                        RoleConstant.ADMIN
                )
                .anyRequest().permitAll();
        // 异常处理
        http.exceptionHandling()
                // 未登录异常
                .authenticationEntryPoint((request, response, exception) -> {
                    if (RequestUtil.isXMLHttpRequest()) {
                        ResponseUtil.sendJSON(R.error(SimpleCode.NO_LOGIN));
                    }else {
                        ResponseUtil.sendRedirect("/login.html");
                    }
                })
                // 没有权限异常
                .accessDeniedHandler((request, response, exception) -> {
                    if (RequestUtil.isXMLHttpRequest()) {
                        ResponseUtil.sendJSON(R.error(SimpleCode.ACCESS_DENIED));
                    }else {
                        RequestUtil.forword("error/404");
                    }
                });
        // Security 底层默认会拦截 /logout 请求，进行退出处理
        // 覆盖它默认的路径，才会执行我们的处理器
        // 退出
        http.logout().logoutUrl("/logoutUrl");
    }

}
